package com.example.xmpic.ui.activity.bind;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import com.example.xmpic.R;
import com.example.xmpic.databinding.ActivityBindWifiBinding;
import com.example.xmpic.support.FunSupport;
import com.example.xmpic.support.FunWifiPassword;
import com.example.xmpic.support.OnFunDeviceWiFiConfigListener;
import com.example.xmpic.support.models.FunDevice;
import com.example.xmpic.support.utils.MyUtils;
import com.example.xmpic.support.utils.StringUtils;
import com.example.xmpic.mvp.contract.CameraIncreaseContract;
import com.example.xmpic.mvp.present.CameraIncreasePresenter;
import com.example.common.base.BasePresentActivity;

/**
 * @author skygge
 * @date 2019-11-27.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：通过Wi-Fi添加
 */
public class CameraConfigInNetActivity extends BasePresentActivity<CameraIncreasePresenter, ActivityBindWifiBinding> implements OnFunDeviceWiFiConfigListener,
		CameraIncreaseContract.IView {

	@Override
	protected int getLayoutId() {
		return R.layout.activity_bind_wifi;
	}

	@Override
	protected void initPresent() {
		super.initPresent();
		mPresent = new CameraIncreasePresenter(mContext);
	}

	@Override
	protected void initView() {
		super.initView();
		FunSupport.getInstance().registerOnFunDeviceWiFiConfigListener(this);
	}

	@Override
	protected void initData() {
		super.initData();
		String mSS_ID = getConnectWifiSSID();
		mDBind.editWifiSSID.setText(mSS_ID);
		mDBind.editWifiPasswd.getCodeEdit().setText(FunWifiPassword.getInstance().getPassword(mSS_ID));
	}

	@Override
	protected void initListener() {
		super.initListener();
		mDBind.ivWifiConfigBack.setOnClickListener(view -> {
			hideSoftKeyboard();
			finish();
		});
		mDBind.btnWifiQuickSetting.setOnClickListener(view -> startQuickSetting());
	}

	// 开始快速配置
	private void startQuickSetting() {
		try {
			WifiManager wifiManage = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
			WifiInfo wifiInfo = wifiManage.getConnectionInfo();
			DhcpInfo wifiDhcp = wifiManage.getDhcpInfo();

			if (null == wifiInfo ) {
				showToast(getString(R.string.device_opt_set_wifi_info_error));
				return;
			}
			
			String ssid = wifiInfo.getSSID().replace("\"", "");
			ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = cm.getActiveNetworkInfo();
			if(ssid.contains("unknow")){
				ssid= networkInfo.getExtraInfo().replace("\"","");
			}
			if ( StringUtils.isStringNULL(ssid) ) {
				showToast(getString(R.string.device_opt_set_wifi_info_error));
				return;
			}

			String wifiPwd = mDBind.editWifiPasswd.getCodeEdit().getText().toString();
			if (  StringUtils.isStringNULL(wifiPwd) ) {
				// 需要密码
				showToast(getString(R.string.device_opt_set_wifi_info_error));
				return;
			}
			int pwdType = networkInfo.getType();
			StringBuffer data = new StringBuffer();
			data.append("S:").append(ssid).append("P:").append(wifiPwd).append("T:").append(pwdType);
			
			String submask;
			if (wifiDhcp.netmask == 0) {
				submask = "255.255.255.0";
			} else {
				submask = MyUtils.formatIpAddress(wifiDhcp.netmask);
			}
			
			String mac = wifiInfo.getMacAddress();
			StringBuffer info = new StringBuffer();
			info.append("gateway:").append(MyUtils.formatIpAddress(wifiDhcp.gateway)).append(" ip:")
					.append(MyUtils.formatIpAddress(wifiDhcp.ipAddress)).append(" submask:").append(submask)
					.append(" dns1:").append(MyUtils.formatIpAddress(wifiDhcp.dns1)).append(" dns2:")
					.append(MyUtils.formatIpAddress(wifiDhcp.dns2)).append(" mac:").append(mac)
					.append(" ");
			
			showProgressDialog(false);
			
			FunSupport.getInstance().startWiFiQuickConfig(ssid,
					data.toString(), info.toString(), 
					MyUtils.formatIpAddress(wifiDhcp.gateway),
					pwdType, 0, mac, -1);
			
			FunWifiPassword.getInstance().saveWifiPassword(ssid, wifiPwd);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void stopQuickSetting() {
		FunSupport.getInstance().stopWiFiQuickConfig();
	}

	private String getConnectWifiSSID() {
		try {
			WifiManager wifimanage=(WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);

			String ssidinit = wifimanage.getConnectionInfo().getSSID().replace("\"", "");
			if(ssidinit.contains("ssid")){
				ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo networkInfo = cm.getActiveNetworkInfo();
				ssidinit = networkInfo.getExtraInfo();
			}
			return ssidinit.replace("\"","");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	@Override
	public void onDeviceWiFiConfigSetted(FunDevice funDevice) {
		if ( null != funDevice ) {
			mPresent.refreshModifyUserInfo(funDevice.getDevSn(),funDevice.getDevName());
		}
	}

	@Override
	public void hasExits() {
		dismissProgressDialog();
		showToast(getString(R.string.device_has_been_exist));
	}

	@Override
	public void showToastMsg(String msg) {
		dismissProgressDialog();
		showToast(msg);
	}

	@Override
	public void bindSuccess() {
		dismissProgressDialog();
		showToast(getString(R.string.success));
		finish();
	}

	@Override
	public void deleteSuccess() {

	}

	@Override
	protected void onDestroy() {
		stopQuickSetting();
		super.onDestroy();
	}
}
